package com.huarui.sale.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.ewaf.framework.dao.impl.BaseDaoImpl;
import org.springframework.orm.ibatis.SqlMapClientCallback;

import com.huarui.sale.dao.ISaleItemDao;
import com.huarui.sale.model.SaleItem;
import com.ibatis.sqlmap.client.SqlMapExecutor;

public class SaleItemDao extends BaseDaoImpl implements ISaleItemDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getSaleItemForMap(Map<String, Object> queryMap) {

		return getSqlMapClientTemplate().queryForList(namespace + ".getSaleItemForMap", queryMap);
	}

	@Override
	public Integer getSaleIdByInventoryIdBySeller(Integer sourceInventoryId) {

		return (Integer) getSqlMapClientTemplate().queryForObject(namespace + ".getSaleIdByInventoryIdBySeller",sourceInventoryId);
	}

	@Override
	public void batchInsertSaleItem(final List<SaleItem> saleItems) {
		getSqlMapClientTemplate().execute(new SqlMapClientCallback() {

			@Override
			public Object doInSqlMapClient(SqlMapExecutor executor)throws SQLException {
				executor.startBatch();
				int batch = 0;
				for (SaleItem saleItem : saleItems) {
					executor.insert(namespace + ".create", saleItem);
					batch++;
					if (batch == 50) {
						executor.executeBatch();
						batch = 0;
					}
				}
				executor.executeBatch();
				return null;
			}
		});

	}

	@Override
	public void batchUpdateSaleItem(final List<SaleItem> saleItems) {
		getSqlMapClientTemplate().execute(new SqlMapClientCallback() {

			@Override
			public Object doInSqlMapClient(SqlMapExecutor executor)throws SQLException {
				executor.startBatch();
				int batch = 0;
				for (SaleItem saleItem : saleItems) {
					executor.update(namespace + ".update", saleItem);
					batch++;
					if (batch == 50) {
						executor.executeBatch();
						batch = 0;
					}
				}
				executor.executeBatch();
				return null;
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public void batchDeleteSaleItemByIds(List<Map> saleItemDeletedIds) {
		for(Map map : saleItemDeletedIds){
			getSqlMapClientTemplate().delete(namespace+".deleteById", map);
		}		
	}

	@SuppressWarnings("unchecked")
	@Override
	public Integer getSaleItemCountByConditions(Map queryMap) {
		return  (Integer) getSqlMapClientTemplate().queryForObject(namespace+".getSaleItemCountByConditions", queryMap);
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map> getSaleItemForMapByConditions(Map queryMap) {
		
		return getSqlMapClientTemplate().queryForList(namespace+".getSaleItemForMapByConditions", queryMap);
	}	
}
